import 'package:flutter/material.dart';

class Toast {
  static OverlayEntry _overlayEntry;
  static bool show = false;
  static DateTime _dateTime;
  static String _msg;

  static void toast(BuildContext context, String msg) async {
    assert(msg != null);
    _msg = msg;
    _dateTime = DateTime.now();
    OverlayState overlayState = Overlay.of(context);
    show = true;
    if (_overlayEntry == null) {
      _overlayEntry = OverlayEntry(
        builder: (BuildContext context) => Positioned(
              top: MediaQuery.of(context).size.height * 4 / 5,
              child: AnimatedOpacity(
                opacity: show ? 1.0 : 0.0,
                duration: show
                    ? Duration(milliseconds: 100)
                    : Duration(milliseconds: 400),
                child: Container(
                  width: MediaQuery.of(context).size.width,
                  alignment: Alignment.center,
                  child: Container(
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.all(Radius.circular(5)),
                      color: Colors.white
                    ),
                    padding: EdgeInsets.all(5),
                    child: Text(
                      _msg,
                      style: TextStyle(
                          fontSize: 14,
                          decoration: TextDecoration.none,
                          color: Colors.black),
                    ),
                  ),
                ),
              ),
            ),
      );
      overlayState.insert(_overlayEntry);
    } else {
      _overlayEntry.markNeedsBuild();
    }

    await Future.delayed(Duration(milliseconds: 2000));

    if (DateTime.now().difference(_dateTime).inMilliseconds >= 2000) {
      show = false;
      _overlayEntry.markNeedsBuild();
    }
  }
}
